package address

import (
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/controllers/login"
	"OnlineRetailers/models/User"
	error2 "OnlineRetailers/models/errorDeal"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type UpdateAddress struct {
	beego.Controller
}

func (c *UpdateAddress) UpdateAddress() {

	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()

	var addr = "/Address/UpdateAddress"
	var err error

	address := &User.Address{}
	log := &error2.Log{}
	mes := &error2.Mes{}
	o := orm.NewOrm()

	err = json.Unmarshal([]byte(c.GetString("address")), address)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	err, openid := login.CheckOpenid(c.Ctx.Request.Header["Openid"])
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	//fmt.Println(address,openid)
	if address.Default {
		user := &User.WXUser{}
		sql := "select `open_id`,`address_id` from `w_x_user` where open_id=?"
		err := o.Raw(sql, openid).QueryRow(user)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
		//fmt.Println(address,openid,*user)
		if user.Address.AddressId != address.AddressId {
			sql = "update `w_x_user` set address_id = ? where open_id =?"
			_, err := o.Raw(sql, address.AddressId, openid).Exec()
			if err != nil {
				c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
				return
			}
		}
	}

	fmt.Println(address)
	//_,err=o.Update(&address)
	//sql:="UPDATE `onlineretailers`.`address` SET `default` = true WHERE `address_id` = '2'"
	sql := "update `address` set `name`=? ,`phone`=? ,`address`=? ,`area`=? , `default` = ? where `address_id`=? and `user_id`=?"

	//sql := "update `address` set `name`='" + address.Name + "',`phone`='" + address.Phone + "',`address`='" + address.Address + "',`area`='" + address.Area + "', `default` = ? where `address_id`=? and `user_id`=?"
	_, err = o.Raw(sql, address.Name, address.Phone, address.Address, address.Area, address.Default, address.AddressId, openid).Exec()
	//_, err = o.Raw(sql).Exec()
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	mes.Mes = "success"
	mes.Code = "200"
	c.Data["json"] = mes
}
